<template>
  <div class="bom">
    <div class="bom-header ">
      <div class="row">
        <div class="col">
          <ul class="list-inline actionbar">
            <li class="list-inline-item" @click="showSelected">显示选中</li>
            <li class="list-inline-item">
              <el-input
                v-model="searchVal"
                placeholder="最少输入3个字符"
                class="search"
                @keyup.enter.native="queryBomListData"
              >
                <el-button
                  slot="append"
                  icon="iconfont iconicon_magnifying"
                  @click="queryBomListData"
                ></el-button>
              </el-input>
            </li>
            <li class="list-inline-item">
              <el-dropdown trigger="click">
                <span class="el-dropdown-link">
                  基本视图<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="item in dropDownBaseView" :key="item.val">{{ item.label }}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </li>
            <li class="list-inline-item border-line">
              <el-dropdown trigger="click">
                <span class="el-dropdown-link">
                  个性化<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>----</el-dropdown-item>
                  <el-dropdown-item>----</el-dropdown-item>
                  <el-dropdown-item>----</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </li>
            <li class="list-inline-item border-line">
              <el-dropdown trigger="click">
                <span class="el-dropdown-link">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>复制</el-dropdown-item>
                  <el-dropdown-item>---</el-dropdown-item>
                  <el-dropdown-item>---</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </li>
          </ul>

        </div>
        <div class="col-auto">
          <el-button-group class="bomAction">
            <el-tooltip
              v-for="(item, k) in radioGroupList"
              :key="k"
              :content="item.tooltipContent"
              placement="top"
            >
              <el-button v-if="['02'].includes(item.value)" :vlaue="item.value" :disabled="multipleSelection.length === 0" @click="clickGroup(item.value)"><i class="iconfont" :class="item.icon"></i> </el-button>
              <el-button v-else-if="['03'].includes(item.value)" :vlaue="item.value" :disabled="!copyData" @click="clickGroup(item.value)"> <i class="iconfont" :class="item.icon"></i> </el-button>
              <el-button v-else-if="['04'].includes(item.value)" :vlaue="item.value" :disabled="multipleSelection.length !== 1" @click="clickGroup(item.value)"> <i class="iconfont" :class="item.icon"></i> </el-button>
              <el-button v-else :vlaue="item.value" @click="clickGroup(item.value)"> <i class="iconfont" :class="item.icon"></i> </el-button>
            </el-tooltip>
          </el-button-group>
        </div>
      </div>
      <!--  -->
    </div>
    <div class="bom-body">
      <div class="table-wrap">
        <!-- highlight-cell -->
        <!-- :edit-config="{trigger: 'click', mode: 'cell', showStatus: true}" -->
        <!-- keep-source -->
        <!-- :pager-config="tablePage" -->
        <vxe-table
          ref="vxeTable"
          v-loading="tLoading"
          class="bomtable-scrollbar"
          border
          resizable
          show-overflow
          :height="tableHeight"
          row-id="id"
          :data="tableData"
          :tree-config="{children: 'children'}"
          :mouse-config="{selected: true}"
          :keyboard-config="{isArrow: true, isDel: true, isTab: true, isEdit: true}"
          @checkbox-change="checkboxChangeEvent"
          @checkbox-all="checkboxChangeEvent"
          @cell-dblclick="headleBomReplace"
        >
          <vxe-table-column type="checkbox" width="40"></vxe-table-column>
          <vxe-table-column
            v-for="(item, index) in tableColumn"
            :key="index"
            :field="item.field"
            :min-width="item.minWidth"
            :title="item.title"
            :edit-render="item.editRender"
            :tree-node="!index"
          ></vxe-table-column>
        </vxe-table>
        <div v-show="isDargMask" class="mask-layer">

        </div>
      </div>
    </div>
    <!-- bom 创建物料  -->
    <dialog-add ref="dialogAdd" />
    <dialog-delete
      ref="dialogDelete"
      :query="{objectBomId:multipleSelection, objectId:id}"
    />
    <!-- 替代料弹窗 -->
    <dialog-alternative-materials ref="dialogAlternativeMaterials" />
    <!--  -->
  </div>
</template>

<script>
import { queryBomList, queryAutoBomList, queryPageBomList, delsObjectbom } from '@/api/frontPage/materials'
import autoTableHeight from '@/utils/autoTableHeight.js'
// import BasicTableColumn from '@/components/frontPage/BasicTableColumn'
import DialogAdd from './components/DialogAdd'
import DialogDelete from './components/DialogDelete'
import DialogAlternativeMaterials from './components/DialogAlternativeMaterials'
import {
  addObjectbom,
  queryLeftTreeData
} from '@/api/frontPage/materials'
import { mapGetters } from 'vuex'
export default {
  name: 'Bom',
  components: {
    // BasicTableColumn,
    DialogDelete,
    DialogAlternativeMaterials,
    DialogAdd
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      copyData: '',
      tableHeight: autoTableHeight(380),
      multipleSelection: [],
      isDargMask: false,
      tablePage: {
        pageSize: 10,
        pageSizes: [10, 15, 20, 50]
      },
      defaultExpandKeys: [],
      searchVal: '',
      Bomloading: false,
      tableData: [],
      tableColumn: [],
      tLoading: false,
      vxeTable: {
        showPopupEdit: false,
        selectRow: null,
        // tableData: [],
        sexList: [
          { label: '女', value: '0' },
          { label: '男', value: '1' }
        ]
      },
      dropDownBaseView: [
        { label: 'BOM视图', val: '01' },
        { label: '替代料视图', val: '02' }
      ],
      radioGroupList: [
        { tooltipContent: '添加', value: '01', icon: 'iconicon_add' },
        { tooltipContent: '删除', value: '02', icon: 'iconicon_trash' },
        { tooltipContent: '粘贴', value: '03', icon: 'iconniantie' },
        { tooltipContent: '替代料', value: '04', icon: 'iconicon_replace' },
        { tooltipContent: '保存', value: '05', icon: 'iconicon_save' },
        { tooltipContent: '返回', value: '06', icon: 'iconicon_cancel' }
      ]
    }
  },
  inject: ['refreshTree'],
  computed: {
    ...mapGetters(['workspaceId'])
  },
  watch: {
    id(val) {
      this.tLoading = true
      // val && this.queryBomListData()
    }

  },
  created() {
    this.queryAutoBomListData()
    this.queryBomListData()
    this.getCopy()
  },
  mounted() {
    this.dragdrop()
  },
  methods: {
    headleBomReplace({ row }) {
      this.$refs.dialogAlternativeMaterials.dbSelectId = row.id
      this.$refs.dialogAlternativeMaterials.dialogVisible = true
    },
    /* bom操作按钮组功能 */
    /* 粘贴 */
    handlePaste() {
      const copyData = JSON.parse(sessionStorage.getItem('bomTableCopyData'))

      addObjectbom({ objectId: this.id, objectBomId: copyData[0].id }).then((res) => {
        this.$message.success('粘贴成功')
        this.queryBomListData()
        this.refreshTree()
        sessionStorage.removeItem('bomTableCopyData')
        this.copyData = ''
      })
    },
    // 接收复制对象
    getCopy() {
      this.copyData = JSON.parse(sessionStorage.getItem('bomTableCopyData'))
    },
    clickGroup(val) {
      switch (val) {
        case '01':
          // 添加
          this.$refs.dialogAdd.dialogVisible = true
          break
        case '02':
          // 删除
          this.$refs.dialogDelete.dialogVisible = true
          break
        case '03':
          // 粘贴
          this.handlePaste()
          break
        case '04':
          // 替换
          this.$refs.dialogAlternativeMaterials.dialogVisible = true
          break
        case '05':
          // 保存
          break
        case '06':
          // 撤销
          break
      }
    },
    /* bom表格操作 */
    /* 单选多选事件 */
    checkboxChangeEvent({ checked, records }) {
      const getCheckbox = this.$refs.vxeTable.getCheckboxRecords()
      this.multipleSelection = getCheckbox.map(el => el.bomObjectId)
    },
    delsObjectbomData() {
      delsObjectbom().then((res) => {
        // this.$message.success(res.message)
      })
    },
    dragdrop() {
      const tableWrap = document.querySelector('.table-wrap')
      const maskLayer = document.querySelector('.mask-layer')
      tableWrap.ondragenter = () => {
        this.isDargMask = true
      }
      maskLayer.ondragleave = () => {
        this.isDargMask = false
      }
      // 拖拽到目标元素上时(不断触发)
      maskLayer.ondragover = () => {
        event.preventDefault() // 只有阻止默认动作后,ondrop才会生效。
      }
      // 拖拽、在目标元素上松开鼠标时 (要先阻止ondragover的默认动作)
      maskLayer.ondrop = () => {
        this.isDargMask = false
        this.$emit('handelDropUpdate')
      }
    },
    showSelected() {},
    /* 获取(对象bom)分页数据列表  */
    queryBomListData() {
      this.tLoading = true
      const query = {
        search: this.searchVal,
        parentId: this.id
      }
      queryBomList(query)
        .then(res => {
          this.tLoading = false
          let result = []
          if (res.result) {
            result = res.result.map(el => ({ ...el, ...el.objectInstance, ...el.objectInstance.attribute }))
          }
          this.tableData = result
        }).catch((res) => {
          this.tLoading = false
        })
    },
    /* 动态获取bom属性列 */
    queryAutoBomListData() {
      queryAutoBomList()
        .then(res => {
          const _tableColumn = (el) => {
            const { label: title, key: field, type } = el
            // 1.物料公有2.bom系统预设3.bom自定义4.基础固定字段
            // const _type = {
            //   '1': 'input',
            //   '2': 'select'
            // }
            // const editRender = { }
            return { title, field, minWidth: '100px' }
          }
          this.tableColumn = res.result.map(_tableColumn)
        })
    },
    /* 获取(对象bom)分页数据列表 */
    queryPageBomListData() {
      const query = {
        'pageNo': 0,
        'pageSize': 0,
        't': {
          'attribute': {},
          'bomObjectId': '',
          'deployVersion': '',
          'description': '',
          'id': '',
          'name': '',
          'nowVersion': '',
          'number': 0,
          'objectCode': '',
          'objectInstance': {
            'attribute': {},
            'baseObjects': {
              'code': '',
              'coderuleId': '',
              'flowId': '',
              'id': '',
              'name': '',
              'objectType': '',
              'remark': '',
              'status': ''
            },
            'code': '',
            'coderuleId': '',
            'createBy': '',
            'createTime': '',
            'delFlag': '',
            'description': '',
            'dictRuleId': '',
            'extendId': '',
            'flag': '',
            'flowId': '',
            'id': '',
            'instanceNumber': '',
            'mainVersion': '',
            'name': '',
            'objectId': '',
            'objectType': '',
            'objversion': '',
            'parentFileId': '',
            'parentObjectId': '',
            'remark': '',
            'smallVersion': '',
            'status': '',
            'unit': '',
            'updateBy': '',
            'updateTime': '',
            'workspaceId': ''
          },
          'parentObjectId': '',
          'remark': '',
          'substituteCount': 0,
          'tag': '',
          'unit': ''
        }
      }
      queryPageBomList(query)
        .then(res => {
          this.tableData = res.result.orders
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/styles/frontPage/mixin';
$pdx14: 14px;
.bomtable-scrollbar ::v-deep .vxe-table--body-wrapper {
  @include scroll;
}
.bom {
  &-header {
    padding: 17px 10px;
    border: 1px solid #EFF2F7;
    border-bottom: none;
  }
  .actionbar {
    margin: 0;
    li.list-inline-item {
      color: #495057;
      margin-right: 18px;
      &.border-line {
        &::before {
          content: "";
          width: 1px;
          margin-right: 16px;
          height: 1.1rem;
          border-left: 1px solid rgba(#495057, 0.5);
        }
      }
    }
  }
  ::v-deep .el-radio-group {
  label {
    margin: 0;
  }
  .bomAction {
    border: none;
    .el-button {
      .iconfont {
        font-size: 12px;
      }
    }
  }
}
  .table-wrap {
    position: relative;
    .mask-layer {
      position: absolute;
      top: 0;
      bottom: 0px;
      left: 0;
      right: 0;
      // background: rgba(0, 0, 0, 0.03);
      z-index: 999999999;
      border: 1px dashed #556de671;
      background: rgba(255, 255, 255, 0.8);
      display: grid;
      font-size: 17px!important;
      font-weight: bold;
      justify-items: center;
      align-items: center;
    }
  }
}
</style>
